package com.wang.ymcc.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.wang.lwm.constents.RedisConstents;
import com.wang.lwm.dto.RegisterCodeInRedis;
import com.wang.lwm.exception.GlobalException;
import com.wang.lwm.result.JSONResult;
import com.wang.lwm.util.AssertUtil;
import com.wang.lwm.util.BitStatesUtils;
import com.wang.ymcc.domain.Login;
import com.wang.ymcc.domain.User;
import com.wang.ymcc.dto.UserDto;
import com.wang.ymcc.feignclient.LoginServerFeign;
import com.wang.ymcc.mapper.UserMapper;
import com.wang.ymcc.service.IUserAccountService;
import com.wang.ymcc.service.IUserBaseInfoService;
import com.wang.ymcc.service.IUserService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 会员登录账号 服务实现类
 * </p>
 *
 * @author whale
 * @since 2022-10-19
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;
    @Autowired
    private LoginServerFeign loginServerFeign;
    @Autowired
    private IUserAccountService userAccountService;

    @Autowired
    private IUserBaseInfoService baseInfoService;

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public void register(UserDto userDto) {
        //1.对数据的校验   验证码，手机号是否注册
        //1.0 查询手机号是否已经注册
        checkData(userDto);
        //保存user并
        Long loginId = saveLoginForApi(userDto);
        //3.生成User对象
        Long userId = saveUser(userDto.getMobile(), loginId);
        //4.生成UserAccount
        userAccountService.save(userId);
        //5.生成UserBeasInfo
        baseInfoService.save(userId,userDto.getRegChannel());

    }

    private Long saveLoginForApi(UserDto dto) {
        Login login = new Login();
        login.setUsername(dto.getMobile());
        login.setPassword(dto.getPassword());
        login.setEnabled(true);
        login.setType(Login.TYPE_WEB);
        JSONResult jsonResult = loginServerFeign.saveOrUpdate(login);
        if(jsonResult.isSuccess()){
            System.out.println(jsonResult.getData());
            System.out.println(jsonResult.getData().getClass());
            Long aLong = Long.valueOf(jsonResult.getData().toString());
            return aLong;
        }else {
            throw new GlobalException(jsonResult.getMessage());
        }

    }
    private Long  saveUser(String phone,long loginId){
        User user = new User();
        user.setCreateTime(new Date().getTime());
        user.setPhone(phone);
        user.setNickName(phone);
        user.setSecLevel(0);
        user.setLoginId(loginId);
        long state1 = BitStatesUtils.addState(BitStatesUtils.OP_REGISTED, BitStatesUtils.OP_ACTIVED);
        long addState = BitStatesUtils.addState(state1, BitStatesUtils.OP_AUTHED_PHONE);
        user.setBitState(addState);
        insert(user);
        return user.getId();
    }
    //1.对数据的校验   验证码，手机号是否注册
    private void checkData(UserDto dto){
        User user = selectByPhone(dto.getMobile());
        /*if(user!=null){
            throw new GlobalException("手机号已经注册，请直接登录");
        }*/
        AssertUtil.isNull(user,"手机号已经注册，请直接登录");
        //1.1 去redis里面获取code
        RegisterCodeInRedis codeInRedis = (RegisterCodeInRedis) redisTemplate.opsForValue().get(RedisConstents.REG_IN_REDIS_PREFIX + dto.getMobile());
        //AssertUtil.isNotNull(codeInRedis,"验证码已过期，请重新发送");
        //AssertUtil.isEqualsTrim(codeInRedis.getCode(),dto.getSmsCode(),"验证码错误");
        /*if(codeInRedis==null){
            throw new GlobalException("验证码已过期，请重新发送");
        }else {
            //1.2 对比code
            if (!codeInRedis.getCode().equals(dto.getSmsCode())) {
                throw new GlobalException("验证码错误");
            }
        }*/
    }

    public User selectByPhone(String phone){
        // where phone=#{phone}
        Wrapper<User> wrapper =new EntityWrapper<>();
        wrapper.eq("phone",phone);
        User user = selectOne(wrapper);
        return  user;
    }



}
